import json
from django.http import HttpResponse
from booking.models import User
import requests
from datetime import date, datetime,timedelta
from django.core.cache import cache


def abtcache(openid):
    ids = cache.get("ids")
    if not ids:
        cache.set('ids',[openid],12*60*60)
    else:
        ids = cache.get('ids')
        if openid not in ids:
            ids.append(openid)
            cache.set('ids',ids,12*60*60)


def login(request):
    data = json.loads(request.body)
    print(data)
    code = data['code']
    appid = 'wx566021081c201091'
    secret = '92762043155d231b7e923cf3eed7836e'
    url = 'https://api.weixin.qq.com/sns/jscode2session' + '?appid=' + appid + '&secret=' + secret + '&js_code=' + code +'&grant_type=authorization_code'
    response = json.loads(requests.get(url).content) #
    if 'errcode' in response:
        return Response(data={'code':response['errcode'], 'msg': response['errmsg']})
    openid = response['openid']
    thisuser = User.objects.filter(openid = openid)
    if thisuser:
        _ = thisuser.first()
        abtcache(openid)
        return HttpResponse(json.dumps({"ret":True,"userdata":{"name":_.name,"uid":_.openid,"url":_.photo,"power":_.power}}))
    session_key = response['session_key']
    url = "https://www.stringzc.top/static/photo.jpg"
    name = "new user"
    times = datetime.now()
    power = 1
    User.objects.create(openid=openid,photo=url,name=name,times=times,power=power,phone = 12345678912)
    abtcache(openid)
    return HttpResponse(json.dumps({"ret":True,"userdata":{"name":name,"uid":openid,"url":url,"power":power}}))


    
